package travelDream.beans;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import traveldream.ejb.DTO.RegistrationDTO;
import traveldream.ejb.interfaces.NotFindException;
import traveldream.ejb.interfaces.ProfileEditBeanLocal;


@ManagedBean(name = "ProfileEM")
@ViewScoped
public class ProfileEditManaged {
	
	private RegistrationDTO reDTO;
	private String user;
	
	private boolean notPrima = false;
	@EJB 
	private ProfileEditBeanLocal ProfileEditBeanLocal;
	
	public void searchByName(){
		if(notPrima == false){
			FacesContext context = FacesContext.getCurrentInstance();
	        ExternalContext externalContext = context.getExternalContext();
	        user = externalContext.getUserPrincipal().getName();
	        try{
	        reDTO = ProfileEditBeanLocal.findUser(user);
	        }
	        catch(NotFindException e){
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error", "Please, logout and login again"));
	        }
	        notPrima = true;
		}
	}
	
	public String save(){
		ProfileEditBeanLocal.save(reDTO);
		return "home.xhtml?faces-redirect=true";
	}

	public RegistrationDTO getReDTO() {
		return reDTO;
	}

	public void setReDTO(RegistrationDTO reDTO) {
		this.reDTO = reDTO;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}
	
	
}
